var levelup = require('level')
var db = levelup('../data')


function put(key, value) {
  return new Promise((reslove, reject) => {
    if (key && value) {
      db.put(key, value, function(error) {
        if (error) {
          reject(error)
        } else {
          reslove()
        }
      })
    } else {
      reject(new Error('no key or value'))
    }
  })
}

function get(key) {
  return new Promise((reslove, reject) => {
    if (key) {
      db.get(key, function(error, value) {
        if (error) {
          reject(error)
        } else {
          reslove(value)
        }
      })
    } else {
      reject(new Error('no key '))
    }
  })
}

function del(key) {
  return new Promise((reslove, reject) => {
    if (key) {
      db.del(key, function(error) {
        if (error) {
          reject(error)
        } else {
          reslove()
        }
      })
    } else {
      reject(new Error('no key '))
    }
  })
}

function batch(arr) {
  return new Promise((reslove, reject) => {
    if (Array.isArray(arr)) {
      var batchList = []
      arr.forEach(item => {
        var listMember = {}
        if (item.hasOwnProperty('type')) {
          listMember.type = item.type
        }
        if (item.hasOwnProperty('key')) {
          listMember.key = item.key
        }
        if (item.hasOwnProperty('value')) {
          listMember.value = item.value
        }
        if (
          listMember.hasOwnProperty('type') &&
          listMember.hasOwnProperty('key') &&
          listMember.hasOwnProperty('value')
        ) {
          batchList.push(listMember)
        }
      })
      if (batchList && batchList.length > 0) {
        db.batch(batchList, function(error) {
          if (error) {
            reject(error)
          } else {
            reslove(batchList)
          }
        })
      } else {
        reject(new Error('array Membre format error'))
      }
    } else {
      reject(new Error('not array'))
    }
  })
}

function find(find, callback) {
  var option = {
    keys: true,
    values: true,
    revers: false,
    limit: 20,
    fillCache: true
  }
  if (!find) return callback('nothing', null)
  else {
    if (find.prefix) {
      option.start = find.prefix
      option.end =
        find.prefix.substring(0, find.prefix.length - 1) +
        String.fromCharCode(
          find.prefix[find.prefix.length - 1].charCodeAt() + 1
        )
    }

    if (find.limit) option.limit = find.limit

    db.createReadStream(option)
      .on('data', function(data) {
        data && callback(data.key, data.value)
      })
      .on('error', function(err) {})
      .on('close', function() {})
      .on('end', function() {
        return callback(null, Date.now())
      })
  }
}

exports.put = put
exports.get = get
exports.del = del
exports.find = find
exports.batch = batch
exports.db = db
